package com.warmheart.base.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class SignResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream buffer = null;

    private ServletOutputStream out = null;

    private PrintWriter writer = null;

    public SignResponseWrapper(HttpServletResponse response) {
        super(response);
        buffer = new ByteArrayOutputStream();
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer, StandardCharsets.UTF_8));
    }

    private class WapperedOutputStream extends ServletOutputStream {

        private ByteArrayOutputStream bos = null;

        public WapperedOutputStream(ByteArrayOutputStream stream) {
            this.bos = stream;
        }

        @Override
        public void write(int b) throws IOException {
            this.bos.write(b);
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }

        @Override
        public boolean isReady() {
            return false;
        }

    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return this.out;
    }

    /**
     * 当获取字符输出流时，实际获取的是我们自己包装的字符输出流
     */
    @Override
    public PrintWriter getWriter() {
        return this.writer;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (this.buffer != null) {
            this.buffer.flush();
        }
        if (this.out != null) {
            this.out.flush();
        }
        if (this.writer != null) {
            this.writer.flush();
        }
    }

    public void close() throws IOException {
        if (this.writer != null) {
            this.writer.close();
        }
        if (this.out != null) {
            this.out.close();
        }
        if (this.buffer != null) {
            this.buffer.close();
        }
    }

    @Override
    public void reset() {
        this.buffer.reset();
    }

    public String getTextContent() throws IOException {
        this.flushBuffer();
        this.close();
        return this.buffer.toString();
    }
}